<template>
  <Category :scane="scane" />
  <el-card style="margin: 10px 0px">
    <el-button
      type="primary"
      icon="Plus"
      :disabled="!categoryStore.c3ID"
      @click="addAttrBut"
      v-show="scane"
    >
      添加属性
    </el-button>
    <div v-show="scane">
      <el-table
        border
        style="margin: 10px 0px; width: 100%"
        v-show="categoryStore.c3ID"
        :data="dataRef"
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="auto"
          min-width="5%"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          width="auto"
          min-width="10%"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值名称" width="auto" min-width="60%">
          <template #="{ row, $index }">
            <el-tag
              style="margin-left: 5px"
              v-for="(item, index) in row.attrValueList"
              :key="item.id"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="auto" min-width="25%">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="addAttrBut"
            ></el-button>
            <el-popconfirm
              :title="`Are you sure to delete ${row.attrName}?`"
              @confirm="deleteAttr($index)"
            >
              <template #reference>
                <el-button icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="!scane">
      <el-from :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-from>
      <el-button
        type="primary"
        @click="addAttrEle"
        icon="Plus"
        :disabled="attrParams.attrName ? false : true"
      >
        添加属性值
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
      <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="auto"
          min-width="5%"
        ></el-table-column>
        <el-table-column label="属性值名称" width="auto" min-width="40%">
          <template #="{ row, $index }">
            <el-input
              placeholder="请输入属性名称"
              v-model="row.valueName"
              v-if="row.flag"
              @blur="toDiv(row, $index)"
              :ref="(vc: any) => (inputArr[$index] = vc)"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作" width="auto" min-width="5%">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              icon="Delete"
              @click="DeleteAttrList($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category'
import { reqAttr, reqAttrOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import type { AttrResponseDate, Attr } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
let categoryStore = useCategoryStore()
let dataRef = ref<Attr[]>([])
let scane = ref<boolean>(true)
let inputArr = ref<any>([])
let attrParams = reactive<Attr>({
  attrName: '',
  categoryId: '',
  attrValueList: [],
  categoryLevel: 3,
})
watch(
  () => categoryStore.c3ID,
  () => {
    dataRef.value = []
    if (!categoryStore.c3ID) return
    getArrtData()
  },
)

const getArrtData = async () => {
  const { c1ID, c2ID, c3ID } = categoryStore
  console.log(c1ID, c2ID, c3ID)
  let result: AttrResponseDate = await reqAttr(c1ID, c2ID, c3ID)
  if (result.code == 200) {
    dataRef.value = result.data
    console.log(result.data)
  }
}
const addAttrEle = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
const addAttrBut = () => {
  scane.value = false
  attrParams.categoryId = categoryStore.c3ID
}
const cancel = () => {
  scane.value = true
}
const save = async () => {
  console.log(attrParams)
  let result: any = await reqAttrOrUpdateAttr(attrParams)
  console.log(result)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}

const toDiv = (row: any, $index: number) => {
  //非法情况判断1
  if (row.valueName.trim() == '') {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  //非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })

  if (repeat) {
    //将重复的属性值从数组当中干掉
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  row.flag = !row.flag
}
const toEdit = (row: any, $index: number) => {
  row.flag = !row.flag
}

// warn :删除属性还是属性值？

const deleteAttr = async (attrId: number) => {
  //发相应的删除已有的属性的请求
  let result: any = await reqRemoveAttr(attrId)
  //删除成功
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //获取一次已有的属性与属性值
    getArrtData()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const DeleteAttrList = (index: number) => {
  attrParams.attrValueList.splice(index, 1)
}
//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  //清空仓库的数据
  categoryStore.$reset()
})
</script>

<style scoped></style>
